<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽健身会员优惠卡</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <style>
        #vcRightInfo p {
            font-size:14px;
            padding-top:2px;
            padding-bottom: 2px;
            margin-top:2px;
            margin-bottom: 2px;
            
            }
        #voucherCardInfo{
            font-size:8px;
            position: absolute;
            right:0;
            bottom:0;
            padding:0 20px 30px 0;
            }
        #voucherCardInfo p{
            font-size:8px;
            margin:3px 0px 3px 0px;
            }
        #vcBg{
            background-color: brown;
            color:#ffffff;
            font-size: 12px;
            position: relative;
            box-shadow: 0 2px 5px rgba(0,0,0,0.8);
            }
        #bgLeftPic{
            display: flex;
            flex-direction: column;
            justify-content: end;
            }
        #bgRight{
            display: flex;
            flex-direction:column;
            justify-content: center;
            align-content: center;
            padding:15px;
            position: absolute;
            top:0;
            right:0;
            width:78%;
            max-width: 90%;
            height:98%;
            word-wrap: break-word;
            white-space: normal;
            }
        #bgRight p{
            margin:4px 0 4px 0;
            }
        #cusNameVc{
            display:block;
            text-align:center;
            font-size:26px;
            margin-bottom: 16px;
            position: absolute;
            right:10px;
            top:16px;
            width:200px;
        }
        #words{            
            display:flex;            
            flex-direction: column;
            justify-content:flex-start;
            align-items: flex-start;
            position: absolute;
            right:10px;
            top:63px;
            width:84%;
            height: 50%;
            text-indent:2em;    
        }
        #words p{            
            padding:1px 0 1px 0;

        }
        #vcName{
            display:block;
            text-align:center;
            font-size:12px;
            margin-bottom: 16px;
            position: absolute;
            right:10px;
            top:96px;
            width:200px;
        }
    </style>
</head>
<body>
    {% include 'show_ins_info.html' %}
    <hr>
    <h2>会员优惠券 / 折扣券查询</h2>
    <div>
        <div class="form-row"><h4 style="width:70px;">会员姓名</h4><input id="cusIdName" style="width: 100px;" oninput="handleInput()"></div>
        <div id="cusList"  style="display: none;"></div>
        <div id='dateBox' class="form-row" style="display:none;"><h4 style="width:70px;">选择日期</h4><select id="dateSel"></select></div> 
        <div id="queryVc"></div>
        <hr style="margin-bottom: 40px;">
        
        <div id="vcBox">
            <div id="preText"></div>
            <div id="vcBg"></div>
        </div>

        <div id="dataMsg"></div>
    </div>


    <script src="../static/js/common.js"></script>
    <script>
        let cus_list;
        let ins_list;
        let buyData;
        let act;
        let vcData;
        let firstItem;
        let vcCfg;
        let vcTxtLib;
        

        document.addEventListener("DOMContentLoaded",function(){
            // loginCheck();
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                // console.log(data);
                    cus_list=data;
                })
                .catch(error => console.error('Error:', error));

                fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('ins list:',data);


                 })
                .catch(error => console.error('Error:', error));

                fetch('/get_vc_cfg')
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('vc cfg:',data);
                vcCfg=data['vc_cfg'];
                vcTxtLib=data['vc_txt'];
                 })
                .catch(error => console.error('Error:', error));



           
        });


      

        function setVcWH(){
            const vcBg=document.getElementById('vcBg');
            const srcWidth=window.innerWidth;
            vcBg.style.width=srcWidth*0.92+'px';
            vcBg.style.height=srcWidth*0.75*0.92+'px';
            vcBg.style.borderRadius='6px';
            vcBg.style.display='flex';
            vcBg.style.flexDirection='row';

        }

        function showVc(){        
            const cusIdName=document.getElementById('cusIdName').value.trim();
            const today=new Date();
            const dataMsg=document.getElementById('dataMsg');
            dataMsg.textContent='';
            fetch('/get_cus_vc_list',{
                    method:"POST",
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body:JSON.stringify({'cusIdName':cusIdName,'today':dateToString(today,'date')})
            })
            .then(response=>response.json())
            .then(data=>{
                console.log('vc card data:',data);
                const queryVc=document.getElementById('queryVc');
                const vcBg=document.getElementById('vcBg');
                if(data['res']==='ok'){
                    queryVc.innerHTML='';        
                    //设置初始卡片大小            
                    setVcWH();                    
                    vcData=data['data'];
                    const cardSelDiv=document.createElement('div');
                    cardSelDiv.classList.add('form-row');
                    const cardSel=document.createElement('select');
                    cardSel.id='vcIdSel';
                    
                    let item;
                    let count=0;

                    vcData.forEach(item=>{
                        if(count===0){
                            firstItem=item;
                        }
                        count+=1;
                        const opt=document.createElement('option');
                        opt.text=item['vc_id'];
                        opt.value=item['vc_id'];
                    
                        cardSel.appendChild(opt);
                    });
                    cardSel.addEventListener('change',showCard);
                    const titleDiv=document.createElement('h4');
                    titleDiv.style.width='70px';
                    titleDiv.textContent='选择卡号';
                    cardSelDiv.appendChild(titleDiv);
                    cardSelDiv.appendChild(cardSel);
                    
                    queryVc.appendChild(cardSelDiv)
                    vcBg.style.display='flex';
                }else{
                    // vcData=undefined;
                    // firstItem=undefined;
                    queryVc.innerHTML='';
                    const vcBg=document.getElementById('vcBg');
                    vcBg.innerHTML='';
                    vcBg.style.display='none';
                    dataMsg.textContent='该会员无卡券';
                }
                
                const vcIdSel=document.getElementById('vcIdSel');
                const eve=new Event('change');
                vcIdSel.dispatchEvent(eve);
            })
            .catch(error=>console.log(error));

            
        }

        function showCard(){
            // console.log(firstItem);
            const today=new Date();
            const cusIdName=document.getElementById('cusIdName').value.trim();
            const vcIdSel=document.getElementById('vcIdSel');
            let vcId;
            let data;
            try{
                vcId=document.getElementById('vcIdSel').value;
                vcData.forEach(item=>{
                    if(item['vc_id']===vcId){
                        data=item;
                    }
                });
                
            }catch(error){
                // console.log(error);
                vcId=firstItem['vc_id'];
                data=firstItem;
            }
  
            
            console.log(data);

            
            const vcBox=document.getElementById('vcBox');
            
            
            const vcBg=document.getElementById('vcBg');
            
            let picLogo='logo_llz.png';
            let bgColor='#A52A2A';
            try{
                bgColor=vcCfg['vc_type_color'][data['use_for']];
                picLogo=vcCfg['vc_type_logo'][data['use_for']];
            }catch(error){
                bgColor=vcCfg['vc_type_color']['default'];
                picLogo=vcCfg['vc_type_logo']['default'];
            }

            console.log('picLogo:',picLogo)
            
            vcBg.innerHTML='';
            const bgLeft=document.createElement('div');
            bgLeft.style.marginLeft='10px';
            bgLeft.id='bgLeftPic';
            bgLeft.innerHTML=`
                <img src="/static/pics/${picLogo}" alt="logo" style="width:140px;height:auto;opacity:1;">
            `;

            const bgRight=document.createElement('div');
            bgRight.id='bgRight';

            const txt=selectTxt(data);

            if(data['use_for']==='common'){
                bgRight.innerHTML=`
                    <div id="cusNameVc"> ${cusIdName.slice(7,)} <span style="font-size:12px;">${data['sex']==='男'?'先生':'女士'}</span></div>
                    <div id="vcName" >${txt}</div>                   
                    <div id="voucherCardInfo">
                        <div id="validPrd" style="text-align: right;color:#f6f4f4"><p>有效期：${dateToString(data['start_date'],'dateChn')}-${dateToString(data['end_date'],'dateChn')}</p><p> 请本人在有效期内使用，过期无效不补。</p></div>
                        <div id="valid" style="text-align: right;"><p>券状态：${data['valid']==='yes'?'有效':'失效'}</p></div>
                        <div id="vcId" style="text-align: right;"><p>券号 <span>${data['vc_id']}</span></p></div>
                        <div id="otherInfo"></div>
                    </div>
            `;
            }else if(data['use_for']==='deposit'){
                bgRight.innerHTML=`
                    <div id="cusNameVc"> ${cusIdName.slice(7,)} <span style="font-size:12px;">${data['sex']==='男'?'先生':'女士'}</span></div>
                    <div id="vcName" >${txt}</div>                   
                    <div id="voucherCardInfo">
                        <div id="validPrd" style="text-align: right;color:#f6f4f4"><p>有效期：${dateToString(data['start_date'],'dateChn')}-${dateToString(data['end_date'],'dateChn')}</p><p> 请本人在有效期内使用，过期无效不补。</p></div>
                        <div id="valid" style="text-align: right;"><p>券状态：${data['valid']==='yes'?'有效':'失效'}</p></div>
                        <div id="vcId" style="text-align: right;"><p>券号 <span>${data['vc_id']}</span></p></div>
                        <div id="otherInfo"></div>
                    </div>
            `;
            }else{
                bgRight.innerHTML=`
                    <div id="cusNameVc"> ${cusIdName.slice(7,)} <span style="font-size:12px;">${data['sex']==='男'?'先生':'女士'}</span></div>
                    <div id="words" >${txt}</div>                   
                    <div id="voucherCardInfo">
                        <div id="validPrd" style="text-align: right;color:#f6f4f4"><p>有效期：${dateToString(data['start_date'],'dateChn')}-${dateToString(data['end_date'],'dateChn')}</p><p> 请本人在有效期内使用，过期无效不补。</p></div>
                        <div id="valid" style="text-align: right;"><p><span style='font-size:6px;'>本卡优惠不与其他优惠活动共同使用</span> 券状态：${data['valid']==='yes'?'有效':'失效'}</p></div>
                        <div id="vcId" style="text-align: right;"><p>券号 <span>${data['vc_id']}</span></p></div>
                        <div id="otherInfo"></div>
                    </div>
            `;

            }

           

            vcBg.appendChild(bgLeft);
            vcBg.appendChild(bgRight);
            if(data['valid']!='yes'){
                vcBg.style.backgroundColor='#8c8a88';
                bgLeft.classList.add('black-and-white');
                const diffDaysStartDate=compareDatesOnly2(today,new Date(data['start_date']));
                const diffDaysEndDate=compareDatesOnly2(today,new Date(data['end_date']));
                document.getElementById('valid').innerHTML=`<p>券状态：失效。</p>`;
                //已过失效期
                if(diffDaysEndDate<0){
                    document.getElementById('valid').innerHTML=`<p>券状态：过期失效。</p>`;
                }
                //还没生效
                if(diffDaysStartDate>0){
                    document.getElementById('valid').innerHTML=`<p>券状态：还未生效。</p>`;
                }
                console.log(diffDaysEndDate,diffDaysStartDate)
                if(data['use_cus_id']!='-'){
                    document.getElementById('valid').innerHTML=`<p>券状态：失效。已由${data['use_cus_name']===cusIdName.slice(7,)?'本人':data['use_cus_name']}使用。</p>`;
                }
                
            }else{
                vcBg.style.backgroundColor=bgColor;
                bgLeft.classList.remove('black-and-white');
            }
            vcBox.appendChild(vcBg);
        }
       

        function selectTxt(data){
            const txtLib=vcTxtLib[data['use_for']];
            let randomTxt = txtLib[Math.floor(Math.random() * txtLib.length)];
            // randomTxt=randomTxt.replace("#amount", `<span style="font-size: 22px;">${hasNonZeroDecimal(data['amount'])?data['amount']:parseInt(data['amount'])}元</span>`).replace("#vc_name", data['vc_name']);
            if(data['use_for']==='cel-birthday'){
                randomTxt=randomTxt.replace("#amount", `<span style="font-size: 22px;">${hasNonZeroDecimal(data['amount'])?data['amount']:parseInt(data['amount'])}元</span>`).replace("#vc_name", data['vc_name']);
            }
            if(data['use_for']==='common'){
                randomTxt=randomTxt.replace("#amount", `<span style="font-size: 28px;">${hasNonZeroDecimal(data['amount'])?data['amount']:parseInt(data['amount'])}元</span>`).replace("#vc_name", data['vc_name']);
            }
            if(data['use_for']==='deposit'){
                randomTxt=randomTxt.replace("#amount", `<span style="font-size: 28px;">${hasNonZeroDecimal(data['amount'])?data['amount']:parseInt(data['amount'])}元</span>`).replace("#vc_name", data['vc_name']);
            }
            
            const lines=randomTxt.split('\n');
            const formattedLines=lines.map(line=>`<p>${line}</p>`).join('');
            return formattedLines

        }

        function handleInput() {
            // 获取输入框中的值
            const searchTerm = document.getElementById("cusIdName").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusList");
            const queryVc=document.getElementById('queryVc');
            queryVc.innerHTML='';
            const vcBg=document.getElementById('vcBg');
            vcBg.style.display='none';
     

            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";

            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.textContent = name;

                    // 添加点击事件监听器
                    listItem.addEventListener("click", function() {
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("cusIdName").value = name;
                        resultList.style.display = "none";
                        resultList.innerHTML = "";
                        showVc();        
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);

                    
                }else{
           

                }
            });
        
            resultList.classList.add("cus-list-result-show");
            resultList.style.top='138px';
            resultList.style.left='212px';
            
        }
      

       
    </script>
    
</body>